#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "usermanage.h"
#include "wifimanage.h"
#include "logininterface.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QFile>
#include <QDir>
#include "view.h"
#include <QGraphicsDropShadowEffect>
#include "messagepops.h"
#include <QTimer>
#include "navigationbar.h"
#include "function/function.h"
#include "operationdocument.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //创建一个文件夹存放下载文件,已经存在返回true
//    QDir dir;
//    dir.mkpath(MY_PATH);//存放药箱插件文件
//    dir.mkpath(QString("%1DigitalVeinUser/").arg(MY_PATH));//存放药箱插件文件
//    configuration();//加载配置文件

    //取消上下标题栏
    setStatusBar(nullptr);
    setMenuBar(nullptr);

    //设置窗口标题
    setWindowTitle("信瑞琅玥");

//    //进入登入界面
//    LoginInterface *login=new LoginInterface();
//    login->show();

    //初始化定时器对象
    deletetime=new QTimer(this);
    //设置定时时间
    deletetime->setInterval(100);  //0.1秒
    //关联timeout()信号与自定义的槽函数
    connect(deletetime,SIGNAL(timeout()),this,SLOT(deletetimer()));



    initialize();//初始化界面

    mps=new MessagePops(this);//初始化提示窗口对象
    mps->hide();
    connect(mps,SIGNAL(sendMessage(QString)),this,SLOT(receMessage(QString)));

    on_pushButton_clicked();//默认进入用户管理界面

//    setHttp();
//    this->hide();//先隐藏该界面，登入成功再显示
}

MainWindow::~MainWindow()
{
    delete ui;
    delete view;
}

void MainWindow::setbytes(QByteArray bytes_,QString name,QWidget *parent)
{
    bytes = bytes_;
    userm->setBytes(bytes);
    userName = name;
    parent_=parent;
    setHttp();
    setHttp2();

    ui->pushButton_4->setText(userName);
}

////显示登入用户信息
//void MainWindow::setview(QString data)
//{

//}

//自定义接收用户管理界面槽函数
void MainWindow::receManMain(int num1, int num2)
{
    if(num1 == 1)
    {
        setHttp();//更新用户信息

        location = num2;
    }
    else if(num1 == 2)
    {
        setHttp();//更新用户信息
        location = num2;
    }
}

//自定义接收WiFi界面槽函数
void MainWindow::receWiFiManage(int num1, int num2)
{
    if(num1 == 1)
    {
        setHttp2();//更新用户信息
        location2 = num2;
    }
    else if(num1 == 2)
    {
        setHttp2();//更新用户信息
        location2 = num2;
    }
}

void MainWindow::receView(QString data)
{
    if(data == "1")
    {

    }
    if(data == "2")
    {
        //给服务器发送退出信号
        QUrl url(URLName_2("logout/"));
        connect(&manager2, SIGNAL(finished(QNetworkReply*)), this, SLOT(recvhttp2(QNetworkReply*)));
        //创建http请求
        QNetworkRequest req(url);
         req.setRawHeader("token",bytes);
        //发送该请求
        manager2.get(req);



    }
}

void MainWindow::receMessage(QString data)
{
    if(data == "2")
    {

    }
    else if(data == "3")
    {

    }
}

void MainWindow::sendNavigationBar(QString data)
{
    if(data == "用户管理")
    {
//        qDebug()<<__LINE__<<"点击了用户管理";
        on_pushButton_clicked();
    }
    else if(data == "WIFI管理")
    {
//        qDebug()<<__LINE__<<"点击了WIFI管理";
        on_pushButton_2_clicked();
    }
}

void MainWindow::deletetimer()
{
    deletetime->stop();//关闭定时器

    delete this;
}



//初始化界面
void MainWindow::initialize()
{
//    font-size: 16px;
//    font-family: Microsoft YaHei;
//    color: #333333;

    //部件事件过滤的注册
    ui->pushButton_3->installEventFilter(this);
    ui->pushButton_4->installEventFilter(this);
    ui->pushButton_5->installEventFilter(this);
    ui->pushButton_6->installEventFilter(this);

    QFont font;
    font.setFamily(QStringLiteral("Microsoft YaHei"));//设置字体
    font.setPixelSize(20);//字体大小
    font.setLetterSpacing(QFont::PercentageSpacing,120);//120字间距，默认100
    ui->pushButton->setFont(font);
    ui->pushButton_2->setFont(font);
    ui->pushButton_4->setFont(font);

    QFont font2;
    font2.setLetterSpacing(QFont::PercentageSpacing,120);//120字间距，默认100
    ui->label_6->setFont(font2);

    NavigationBar *navigationBar = new NavigationBar(this);
    connect(navigationBar,SIGNAL(sendNavigationBar(QString)),this,SLOT(sendNavigationBar(QString)));
    navigationBar->setGeometry2(0, 100, 300, 600);
    navigationBar->setPbStyleone(1);
    navigationBar->show();


    wifim = new WiFiManage(this);
    connect(wifim,SIGNAL(sendWiFiManage(int, int)),this,SLOT(receWiFiManage(int, int)));
    wifim->setGeometry(ui->label->geometry().x()+1,ui->label->geometry().y()+1,ui->label->width()-2,ui->label->height()-2);

    userm = new UserManage(this);
    connect(userm,SIGNAL(sendManMain(int, int)),this,SLOT(receManMain(int, int)));

    userm->setGeometry(ui->label->geometry().x()+1,ui->label->geometry().y()+1,ui->label->width()-2,ui->label->height()-2);

    //设置帮助按钮图片
//    ui->pushButton_3->setIcon(QPixmap(":/new/prefix1/resource/8.png").scaled(25,22));

    //设置用户信息按钮
//    //设置具体阴影
//    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
//    shadow_effect->setOffset(0, 0);

//    //阴影颜色
//    shadow_effect->setColor(QColor(38, 78, 119, 127));
//    //阴影半径
//    shadow_effect->setBlurRadius(10);
//    ui->pushButton_4->setGraphicsEffect(shadow_effect);

    view = new View(this);
    connect(view,SIGNAL(sendView(QString)),this,SLOT(receView(QString)));
    view->hide();



}

//点击WiFi管理界面按钮
void MainWindow::on_pushButton_2_clicked()
{
//    wifim = new WiFiManage(this);
//    wifim->setGeometry(ui->label->geometry().x(),ui->label->geometry().y(),ui->label->width(),ui->label->height());

    ui->pushButton->setStyleSheet("background:rgba(255, 255, 255, 0%);padding-right:4px;");
    ui->pushButton_2->setStyleSheet("background: #F1F6F9;border-style: solid;border-right:4px solid #1B89CC;color: #333333;");

    userm->close();
    wifim->show();
}

//点击用户管理界面按钮
void MainWindow::on_pushButton_clicked()
{
//    userm = new UserManage(this);
//    userm->setGeometry(ui->label->geometry().x(),ui->label->geometry().y(),ui->label->width(),ui->label->height());

    ui->pushButton_2->setStyleSheet("background:rgba(255, 255, 255, 0%);padding-right:4px;");
    ui->pushButton->setStyleSheet("background: #F1F6F9;border-style: solid;border-right:4px solid #1B89CC;color: #333333;");

    wifim->close();
    userm->show();
}

void MainWindow::recvhttp2(QNetworkReply *reply)
{
    //读取http应答信息
   QByteArray buf=reply->readAll();
//   if(buf.isEmpty())
//   {
//       return;
//   }
   qDebug()<<__LINE__<<QString(buf);

   //把获取的json数据标准化存储
   QJsonParseError myerr;
   QJsonDocument mydoc=QJsonDocument::fromJson(buf,&myerr);

   //获取最外面的对象
   QJsonObject obj=mydoc.object();

   QString message=obj.value("message").toString();
   qDebug()<<__LINE__<<"message="<<message;

   if(message == "退出成功")
   {
        //返回登入界面
        LoginInterface *lif = (LoginInterface *)parent_;
        lif->show();
        lif->clearPassword();//清除密码

        //关闭当前界面--》主界面
        deletetime->start();
   }
   else
   {
       mps->setText("退出失败");
       mps->show();
   }

}

//请求http获取信息
void MainWindow::setHttp()
{
    //获取医护人员信息：
    QUrl url3(URLName_2("user-list/"));
    connect(&manager3, SIGNAL(finished(QNetworkReply*)), this, SLOT(recvhttp3(QNetworkReply*)));
    //创建http请求
    QNetworkRequest req3(url3);
     req3.setRawHeader("token",bytes);
    //发送该请求
     manager3.get(req3);
}

void MainWindow::setHttp2()
{
    //获取WIFI信息：
    QUrl url4(URLName_2("wifi-list/"));
    connect(&manager4, SIGNAL(finished(QNetworkReply*)), this, SLOT(recvhttp4(QNetworkReply*)));
    //创建http请求
    QNetworkRequest req4(url4);
     req4.setRawHeader("token",bytes);
    //发送该请求
     manager4.get(req4);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(ui->pushButton_3==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }
    if(ui->pushButton_4==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }
    if(ui->pushButton_5==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }
    if(ui->pushButton_6==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }

    return QObject::eventFilter(watched,event);
}

//加载配置文件
void MainWindow::configuration()
{
    QString path = OperationDocument::searchConfigFile("client.ini");
    //创建QFile
    QFile myfile(path);
    //打开文件
    bool ret=myfile.open(QIODevice::ReadOnly);
    if(!ret)
    {
        qDebug()<<__LINE__<<"打开配置文件失败"<<"path="<<path;
        return;
    }
    while(!myfile.atEnd())
    {
        //读取一行数据
        QByteArray array=myfile.readLine();
        QString buf;
//        buf = array.replace(" ","");
        buf = array.replace("\r","");
        buf = array.replace("\n","");

        QStringList mylist = buf.split("##");//如果有注释则解析掉注释部分
        QStringList list = mylist.at(0).split("=");
        if(list.size() < 2) continue;


        if(list.at(0) == "IpPort")
        {
            IpPort = list.at(1);
            qDebug()<<__LINE__<<"服务器ip端口号"<<"IpPort="<<IpPort;
        }
        else if(list.at(0) == "IpPort_2")
        {
            IpPort_2 = list.at(1);
            qDebug()<<__LINE__<<"服务器ip端口号"<<"IpPort_2="<<IpPort_2;
        }
    }

    myfile.close();
}

void MainWindow::recvhttp3(QNetworkReply *reply)
{
    //读取http应答信息
   QByteArray buf=reply->readAll();
   if(buf.isEmpty())
   {
       return;
   }
//   qDebug()<<__LINE__<<QString(buf);

    medicalWorkersData = buf;

   //根据实际填写路径,把信息保存在本地
   QFile file(QString("%1医护人员数据.json").arg(MY_PATH));
   if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate))
   {
       qDebug() << __LINE__ << "file error!";
   }
   QTextStream stream(&file);
   stream.setCodec("UTF-8");		// 设置写入编码是UTF8
   // 写入文件
   stream << QString(buf);
//   QTextStream in(&file);
//   in << QString(buf);
   file.close();   // 关闭file

   userm->analysisMedicalWorkers(medicalWorkersData, location);

}

void MainWindow::recvhttp4(QNetworkReply *reply)
{
    //读取http应答信息
   QByteArray buf=reply->readAll();
   if(buf.isEmpty())
   {
       return;
   }
//   qDebug()<<QString(buf);

   medicalWiFiData = buf;

  //根据实际填写路径,把信息保存在本地
  QFile file(QString("%1WIFI数据.json").arg(MY_PATH));
  if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate))
  {
      qDebug() << __LINE__  << "file error!";
  }
  QTextStream stream(&file);
  stream.setCodec("UTF-8");		// 设置写入编码是UTF8
  // 写入文件
  stream << QString(buf);
//   QTextStream in(&file);
//   in << QString(buf);
  file.close();   // 关闭file

  wifim->analysisWiFiWorkers(medicalWiFiData, location2);
}

//点击用户信息按钮
void MainWindow::on_pushButton_4_clicked()
{
    QPoint g_p = mapToGlobal(ui->pushButton_4->pos());	//控件左上角在显示器的坐标
    int x = g_p.x();
    int y = g_p.y();

    view->setGeometry(x-5,y-5,194,130);
    view->setview(userName);
    view->show();
}

void MainWindow::on_pushButton_5_clicked()
{
    on_pushButton_4_clicked();
}

void MainWindow::on_pushButton_6_clicked()
{
    on_pushButton_4_clicked();
}
